package com.qiku.web.servlet;

import com.qiku.pojo.User;
import com.qiku.service.UserService;
import com.qiku.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "registerServlet",urlPatterns = "/register" )
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private User user = new User();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置文本格式
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String is_root = req.getParameter("is_root");
        user.setUsername(username);
        user.setPassword(password);
        if (is_root != null){
            if (is_root.equals("1") || is_root.equals("0"))
                user.setIs_root(Integer.parseInt(is_root));
        }else{
            user.setIs_root(0);
        }
        String str = userService.userRegister(user);
        switch (str) {
            case "success":
                resp.sendRedirect("login.jsp");
                break;
            case "fail":
                //返回提示信息
                req.setAttribute("error", "用户注册失败！");
                //获取转发器  并指定转发路径
                req.getRequestDispatcher("register.jsp").forward(req, resp);
                break;
            case "msg":
                //返回提示信息
                req.setAttribute("error", "用户已存在！");
                //获取转发器  并指定转发路径
                req.getRequestDispatcher("register.jsp").forward(req, resp);
            case "null":
                //返回提示信息
                req.setAttribute("error", "用户名和密码不能为空！");
                //获取转发器  并指定转发路径
                req.getRequestDispatcher("register.jsp").forward(req, resp);
            default:
                System.out.println("未知错误...");
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
